// points.js
Page({
  data: {
    totalPoints: 0,
    availablePoints: 0,
    usedPoints: 0,
    pointsHistory: [],
    loading: false,
    userInfo: {
      isLogin: false
    }
  },

  onLoad() {
    this.loadUserInfo()
    this.loadPointsData()
  },

  onShow() {
    this.loadPointsData()
  },

  // 加载用户信息
  loadUserInfo() {
    const app = getApp()
    const userInfo = app.getUserInfo()
    this.setData({ userInfo })
  },

  // 加载积分数据
  loadPointsData() {
    if (!this.data.userInfo.isLogin) {
      this.setData({ 
        totalPoints: 0,
        availablePoints: 0,
        usedPoints: 0,
        pointsHistory: []
      })
      return
    }

    this.setData({ loading: true })
    this.getPointsDataFromAPI()
  },

  // 从API获取积分数据
  getPointsDataFromAPI() {
    wx.request({
      url: 'http://localhost:8082/user/points',
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        this.setData({ loading: false })
        
        if (res.data && res.data.code === 200) {
          const data = res.data.data
          this.setData({
            totalPoints: data.totalPoints || 0,
            availablePoints: data.availablePoints || 0,
            usedPoints: data.usedPoints || 0,
            pointsHistory: data.pointsHistory || []
          })
        } else {
          this.setData({
            totalPoints: 0,
            availablePoints: 0,
            usedPoints: 0,
            pointsHistory: []
          })
        }
      },
      fail: (err) => {
        console.error('获取积分数据失败:', err)
        this.setData({ 
          loading: false,
          totalPoints: 0,
          availablePoints: 0,
          usedPoints: 0,
          pointsHistory: []
        })
      }
    })
  },

  // 积分兑换
  onPointsExchange() {
    wx.showActionSheet({
      itemList: ['10积分=1元', '100积分=10元', '1000积分=100元', '自定义兑换'],
      success: (res) => {
        const rates = [
          { points: 10, amount: 1 },
          { points: 100, amount: 10 },
          { points: 1000, amount: 100 },
          { points: 0, amount: 0 } // 自定义
        ]
        
        const rate = rates[res.tapIndex]
        
        if (rate.points === 0) {
          // 自定义兑换
          wx.showModal({
            title: '自定义兑换',
            editable: true,
            placeholderText: '请输入积分数量',
            success: (modalRes) => {
              if (modalRes.confirm && modalRes.content) {
                const points = parseInt(modalRes.content)
                if (points > 0 && points <= this.data.availablePoints) {
                  const amount = Math.floor(points / 10)
                  this.processPointsExchange(points, amount)
                } else {
                  wx.showToast({
                    title: '积分数量无效',
                    icon: 'none'
                  })
                }
              }
            }
          })
        } else {
          if (this.data.availablePoints >= rate.points) {
            this.processPointsExchange(rate.points, rate.amount)
          } else {
            wx.showToast({
              title: '积分不足',
              icon: 'none'
            })
          }
        }
      }
    })
  },

  // 处理积分兑换
  processPointsExchange(points, amount) {
    wx.showModal({
      title: '确认兑换',
      content: `确定要用${points}积分兑换${amount}元吗？`,
      success: (res) => {
        if (res.confirm) {
          // 模拟兑换成功
          const newAvailablePoints = this.data.availablePoints - points
          const newUsedPoints = this.data.usedPoints + points
          
          const newRecord = {
            id: Date.now(),
            type: 'exchange',
            points: -points,
            description: `积分兑换${amount}元`,
            time: new Date().toLocaleString(),
            status: 'success'
          }
          
          this.setData({
            availablePoints: newAvailablePoints,
            usedPoints: newUsedPoints,
            pointsHistory: [newRecord, ...this.setData.pointsHistory]
          })
          
          wx.showToast({
            title: '兑换成功',
            icon: 'success'
          })
        }
      }
    })
  },

  // 查看积分规则
  onViewRules() {
    wx.showModal({
      title: '积分规则',
      content: '1. 每日签到可获得10积分\n2. 完成课程学习可获得50积分\n3. 购买商品可获得消费金额×10的积分\n4. 积分可用于兑换现金\n5. 积分有效期为1年',
      showCancel: false
    })
  },

  // 签到
  onCheckIn() {
    wx.showLoading({
      title: '签到中...'
    })
    
    // 模拟签到API调用
    setTimeout(() => {
      wx.hideLoading()
      
      const newRecord = {
        id: Date.now(),
        type: 'checkin',
        points: 10,
        description: '每日签到',
        time: new Date().toLocaleString(),
        status: 'success'
      }
      
      this.setData({
        totalPoints: this.data.totalPoints + 10,
        availablePoints: this.data.availablePoints + 10,
        pointsHistory: [newRecord, ...this.data.pointsHistory]
      })
      
      wx.showToast({
        title: '签到成功，获得10积分',
        icon: 'success'
      })
    }, 1000)
  },

  // 去登录
  goToLogin() {
    wx.navigateTo({
      url: '/pages/login/login'
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadPointsData()
    wx.stopPullDownRefresh()
  }
})
